import { HOST } from '../core/dict';
import logger from '../core/logger';
import { clientBase } from './clientBase';
import ajaxResult from '../models/apis/ajaxResult';
import { userInfo } from '../models/apis/userInfo';
import axios, { AxiosError, AxiosResponse } from '@ohos/axios';

class userClient extends clientBase {
  constructor() {
    super();
  }

  public login(data: userInfo): Promise<ajaxResult<userInfo>> {
    return new Promise((resolve) => {
      axios.post<string, AxiosResponse<string>, any>(`${HOST}api/user/login`, data)
        .then((response: AxiosResponse) => {
          if (response.status == 200) {
            let ret: userInfo = response.data.result;
            resolve(this.buildSuccessResult<userInfo>(ret));
          } else
            resolve(this.buildFailedResult<userInfo>(response.statusText));
        }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.buildExceptionResult<userInfo>(err));
        });
    });
  }

  public register(data: userInfo): Promise<ajaxResult<number>> {
    return new Promise((resolve) => {
      axios.post<string, AxiosResponse<string>, any>(`${HOST}api/user/reg`, data)
        .then((response: AxiosResponse) => {
          if (response.status == 200) {
            let ret: number = response.data;
            resolve(this.buildSuccessResult<number>(ret));
          } else
            resolve(this.buildFailedResult<number>(response.statusText));
        }).catch((err: AxiosError) => {
          logger.error(err);
          resolve(this.buildExceptionResult<number>(err));
        });
    });
  }

  public getInfo(userId: string): Promise<ajaxResult<userInfo>> {
    return new Promise((resolve) => {
      axios.get<string, AxiosResponse<string>, null>(`${HOST}api/user/getInfo?userId=${userId}`)
        .then((response: AxiosResponse) => {
          if (response.status == 200) {
            let ret: userInfo = response.data.result;
            resolve(this.buildSuccessResult<userInfo>(ret));
          } else
            resolve(this.buildFailedResult<userInfo>(response.statusText));
        }).catch((err: AxiosError) => {
        logger.error(err);
        resolve(this.buildExceptionResult<userInfo>(err));
      });
    });
  }
}
export default new userClient();